package com.itheima.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.dto.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.KSQLWindow;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.List;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/dish")
@RestController
public class DishConterllor {
    @Autowired
    DishService dishService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /*
     * 菜品分页+模糊查询*/
    @GetMapping("/page")
    public R<Page> selectPage(int page, int pageSize, String name) {

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        wrapper.orderByDesc(Dish::getUpdateTime);
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDaoPage = new Page<>(page, pageSize);
        dishService.page(dishPage, wrapper);
        //dishDaoPage对象拷贝
        BeanUtils.copyProperties(dishPage, dishDaoPage, "records");

        //获取dishPage的records数据
        List<Dish> records = dishPage.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //将dish的值赋值给dishdao
            BeanUtils.copyProperties(item, dishDto);
            //获取到categoryId
            Long categoryId = item.getCategoryId();
            //通过categoryId获取到category
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //通过category获取到categoryName并赋值给dishDto
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //将得到的DishDto集合赋值给dishDaoPage
        dishDaoPage.setRecords(list);


        return R.success(dishDaoPage);

    }

    /*
     * 新增菜品*/
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlaver(dishDto);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);//删除这些key

        /*//清理某个菜品分类下的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/
        return R.success("新增菜品成功");
    }

    /*
     * 根据id查询菜品数据，用于回显*/
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlaver(id);
        return R.success(dishDto);
    }

    /*
     * 修改菜品*/
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlaver(dishDto);

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);//删除这些key

        /*//清理某个菜品分类下的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/

        return R.success("菜品修改成功");
    }

    /*
     * 批量删除+菜品
     **/
    @DeleteMapping
    public R<String> deleteIds(@RequestParam List<Long> ids) {
        dishService.deleteIds(ids);
        return R.success("删除成功");
    }

    /*
     * 起售/停售 批量起售/批量停售*/
    @PostMapping("/status/{status}")
    public R<String> statusIds(@PathVariable Integer status, @RequestParam List<Long> ids) {


        for (Long id : ids) {
            //获取id对应的菜品数据
            Dish dish = dishService.getById(id);
            //将传过来的status赋值给dish
            dish.setStatus(status);
            //完成修改
            dishService.updateById(dish);
        }

        return R.success("操作成功");

    }

    /*
     * 根据分类id查询改分类下的所有菜品集合*/
    @GetMapping("/list")
    public R<List<DishDto>> getById(Dish dish) {
        List<DishDto> dishDtoList = null;
        //动态构造key
        //dish_1397844391040167938_1
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null) {
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }


        //创建条件构造器
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        wrapper.eq(Dish::getStatus, 1);
        //对添加时间进行排序
        wrapper.orderByDesc(Dish::getUpdateTime).orderByDesc(Dish::getSort);
        //封装数据到集合

        List<Dish> dishList = dishService.list(wrapper);
        dishDtoList = dishList.stream().map(item -> {

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            //分类名称
            //获取到categoryId
            Long categoryId = item.getCategoryId();
            //通过categoryId获取到category
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //通过category获取到categoryName并赋值给dishDto
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //菜品口味数据到DishDto
            LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            flavorLambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> list = dishFlavorService.list(flavorLambdaQueryWrapper);
            dishDto.setFlavors(list);

            return dishDto;
        }).collect(Collectors.toList());

        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到redis
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);

        return R.success(dishDtoList);
    }

}
